<template>
    <div class="common-layout">
        <el-container>
            <!-- 头部部分 --> 
            <el-header>
                <el-row justify="space-between" align="middle">
                    <el-col :span="6">
                        <div class="breadcrumb">
                            <el-icon><Fold /></el-icon>
                            <span>运营</span>
                        </div>
                    </el-col>
                    <el-col :span="3">
                        <div class="user-info">
                            <el-avatar :size="30" src="" />
                            <span class="username">admin</span>
                        </div>
                    </el-col>
                </el-row>
            </el-header>
            <el-header class="white"></el-header>
            <!--内容部分-->
            <el-main>
                <!--搜索部分-->
                <el-header class="search">
                    <el-input v-model="search" style="width: 240px" placeholder="请输入题目" />
                    <el-button type="primary">搜索</el-button>
                </el-header>
                <!--添加/刷新部分-->
                <el-header class="add-refresh">
                    <el-button type="danger" @click="handleAdd">
                       <el-icon><Plus /></el-icon>
                       添加
                    </el-button>
                    <el-button type="info" @click="handleRefresh">
                       <el-icon><Refresh /></el-icon>
                       刷新
                    </el-button>
                </el-header>
                <!--表格部分-->
                <el-table :data="tableData" border style="width: 100%">
                    <el-table-column prop="id" label="编号" width="10%" ></el-table-column>
                    <el-table-column #default="scope" width="20%" label="封面图">
                        {{ scope.row.coverImage }}
                        <el-image 
                            v-if="scope.row.image" 
                            :src="`${scope.row.image}`" 
                            style="width: 40px; height: 40px"
                            fit="cover"
                            fallback="https://via.placeholder.com/40x40?text=加载失败"
                            />
                        <span v-else class="no-image">无图片</span>
                        <!-- <img :src="{{ scope.row.coverImage }}" alt=""/> -->
                    </el-table-column>
                    <el-table-column prop="title" label="标题" width="10%"></el-table-column>
                    <el-table-column prop="columnName" label="所属栏目" width="10%" ></el-table-column>
                    <el-table-column prop="isShow" label="是否显示" width="10%" ></el-table-column>
                    <el-table-column prop="isTop" label="是否置顶" width="10%"></el-table-column>
                    <el-table-column prop="createdAt" label="添加日期" width="10%" ></el-table-column>
                    <el-table-column label="操作" width="20%" >
                        <template #default="scope">
                            <el-button 
                            class="edit"
                            size="small" 
                            type="primary" 
                            @click="handleEdit(scope.$index, scope.row)"
                            >
                            <el-icon><Edit /></el-icon>
                            编辑
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                 <!-- 添加/编辑弹窗 -->
                <el-dialog 
                    v-model="dialogVisible" 
                    :title="dialogTitle"  
                    width="600px"
                    :close-on-click-modal="false"  
                >
                    <!-- 弹窗表单：与form变量双向绑定 -->
                    <el-form :model="form" label-width="120px" class="dialog-form">
                        <!-- 1. 标题 -->
                        <el-form-item label="标题" prop="title" required>
                            <el-input 
                                v-model="form.title" 
                                placeholder="请输入标题" 
                                maxlength="100"
                            />
                        </el-form-item>

                        <!-- 2. 所属栏目 -->
                        <el-form-item label="所属栏目" prop="column" required>
                            <el-select v-model="form.column" placeholder="请选择所属栏目">
                                <el-option label="企业动态" value="企业动态" />
                                <el-option label="设备持有人" value="设备持有人" />
                                <el-option label="行业资讯" value="行业资讯" />
                            </el-select>
                        </el-form-item>

                        <!-- 3. 封面图 -->
                        <el-form-item label="封面图">
                            <el-upload
                                class="avatar-uploader"
                                action="http://106.13.143.56:8080/garbageSys/commit/uploadImage"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload"
                                :headers="uploadHeaders"
                            >
                                
                                <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="无法加载" />
                                <div v-else class="avatar-uploader-icon">
                                <el-icon><Plus /></el-icon>
                                <!-- <p>点击上传</p> -->
                                </div>
                            </el-upload>
                        </el-form-item>

                        <!-- 4. 内容 -->
                        <el-form-item label="内容" prop="content" required>
                            <el-input
                                v-model="form.content"
                                type="textarea"
                                :rows="6"
                                placeholder="请输入内容"
                            />
                        </el-form-item>

                        <!-- 5. 是否显示 -->
                        <el-form-item label="是否显示">
                            <el-radio-group v-model="form.visible">
                                <el-radio :value="1" size="large">是</el-radio>
                                <el-radio :value="0" size="large">否</el-radio>
                            </el-radio-group>
                        </el-form-item>

                        <!-- 6. 是否置顶 -->
                        <el-form-item label="是否置顶">
                            <el-radio-group v-model="form.pin">
                                <el-radio :value="1" size="large">是</el-radio>
                                <el-radio :value="0" size="large">否</el-radio>
                            </el-radio-group>
                        </el-form-item>

                        <!-- 7. 是否弹窗 -->
                        <el-form-item label="是否弹窗">
                            <el-radio-group v-model="form.popup">
                                <el-radio :value="1" size="large">是</el-radio>
                                <el-radio :value="0" size="large">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-form>

                    <!-- 弹窗底部按钮：取消/确定 -->
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="dialogVisible = false">取消</el-button>
                            <el-button type="primary" @click="handleSubmit">确定</el-button>
                        </span>
                    </template>
                </el-dialog>

            </el-main>
        
        </el-container>
    </div>
</template>

<script setup>
import { ref, reactive, computed,onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getlist,addDeviceNotice } from '@/components/Operation/seekAdviceFrom'

//搜索栏
const search = ref('')
// 弹窗控制
const dialogVisible = ref(false)
const isEditing = ref(false)
const currentEditIndex = ref(-1)

// 计算弹窗标题
const dialogTitle = computed(() => {
    return isEditing.value ? '编辑内容' : '添加内容'
})

// 表单数据
const form = reactive({
    title: '',
    column: '',
    img: '',
    content: '',
    visible: 1, // 1:是, 0:否
    pin: 0,     // 1:是, 0:否
    popup: 0    // 1:是, 0:否
})
let show=async ()=>{
    await getlist().then((res)=>{
        if(res.code>=200){
            console.log(res.dataset);
            tableData.value=res.dataset
        }
        
    })
}
onMounted(() => {
  show()
})
// 表格数据
const tableData = ref([
])

// 添加按钮点击事件
const handleAdd =async () => {
    isEditing.value = false
    currentEditIndex.value = -1
    // 重置表单
    Object.assign(form, {
        title: '',
        column: '',
        img: '',
        content: '',
        visible: 1,
        pin: 0,
        popup: 0
    })
    dialogVisible.value = true

    
    //添加
    // try {
    //     let res=await addDeviceNotice()
    //     console.log(res);
        
    // } catch (error) {
    //     console.log(error);
        
    // }
}

// 编辑按钮点击事件
const handleEdit = (index, row) => {
    isEditing.value = true
    currentEditIndex.value = index
    
    // 填充表单数据
    Object.assign(form, {
        title: row.title,
        column: row.column,
        img: row.img,
        content: '', // 这里需要根据实际数据结构调整
        visible: row.visible === '是' ? 1 : 0,
        pin: row.pin === '是' ? 1 : 0,
        popup: 0 // 默认值，需要根据实际数据结构调整
    })
    dialogVisible.value = true
}

// 表单提交
const handleSubmit = async() => {
    console.log(form,12313);
    // 表单验证
    if (!form.title.trim()) {
        ElMessage.error('请输入标题')
        return
    }
    if (!form.column) {
        ElMessage.error('请选择所属栏目')
        return
    }
    if (!form.content.trim()) {
        ElMessage.error('请输入内容')
        return
    }

    if (isEditing.value) {
        // 编辑模式
        const item = tableData.value[currentEditIndex.value]
        item.title = form.title
        item.column = form.column
        item.img = form.img
        item.visible = form.visible ? '是' : '否'
        item.pin = form.pin ? '是' : '否'
        ElMessage.success('编辑成功')
    } else {
        // 添加模式
        const newItem = {
            id: String(parseInt(tableData.value[tableData.value.length - 1]?.id || 0) + 1),
            img: form.img,
            title: form.title,
            column: form.column,
            visible: form.visible ? '是' : '否',
            pin: form.pin ? '是' : '否',
            date: new Date().toLocaleDateString('zh-CN').replace(/\//g, '.')
        }
        try {
            let res=await addDeviceNotice(form)
            console.log(res);
            
        } catch (error) {
            console.log(error);
            
        }
        ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
}

// 图片上传处理
const beforeAvatarUpload = (rawFile) => {
  const isJPG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
  if (!isJPG) {
    ElMessage.error('请上传JPG或PNG格式的图片!')
    return false
  }
  const isLt2M = rawFile.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
};
//token
const uploadHeaders = computed(() => {
  return {
    token: sessionStorage.getItem('token') || '' // 每次请求都实时获取
  };
});
//上传成功
let imageUrl=ref()
const handleAvatarSuccess = (response, uploadFile) => {
  if (response.code === 200) {
    const serverDomain = 'http://106.13.143.56:8080/garbageSys/images';
    const fullImageUrl = serverDomain + response.dataset.filePath;
    imageUrl.value = fullImageUrl;
    form.img = fullImageUrl; // 存储完整图片地址
  } else {
    ElMessage.error('图片上传失败：' + (response.msg || '未知错误'))
  }
}
// 刷新页面函数
const handleRefresh = () => {
  window.location.reload()
}
</script>


<!--css样式-->
<style lang="less" scoped>
/* 头部部分 */
.el-header{
    height: 40px;
    border-bottom: 1px solid rgb(187, 186, 186);
}
.breadcrumb{
    display: flex;
    align-items: center;
}
.user-info{
    display: flex;
    align-items: center;
    gap: 8px;  
}
.white{
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
/*内容部分*/
.el-main{
    padding: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
}
/*搜索部分*/
.search{
    width: 100%;
    border: none;
    margin: 20px 0;
    display: flex;
    align-items: center;
    gap:10px;
}
/*添加/刷新部分*/
.add-refresh{
    width: 100%;
    border: none;
    margin: 20px 0;
    display: flex;
    align-items: center;
    justify-content: right;
}
/*数据表格部分*/
::v-deep .el-table .el-table__header {
  width: 100% !important;
}
::v-deep .el-table .el-table__body {
  width: 100% !important;
}
::v-deep .el-table .el-table__row {
  height: 80px;
}

/* 图片上传样式 */
::v-deep(.avatar-uploader) {
    .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
        width: 120px;
        height: 120px;
        display: flex;
        align-items: center;
        justify-content: center;
        
        &:hover {
            border-color: var(--el-color-primary);
        }
    }
}

::v-deep(.avatar-uploader-icon) {
    font-size: 28px;
    color: #8c939d;
}

::v-deep(.avatar) {
    width: 120px;
    height: 120px;
    display: block;
    object-fit: cover;
}
</style>